package com.danskin.wechat.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.mp.aes.AesException;
import org.jeewx.api.third.JwThirdAPI;
import org.jeewx.api.third.model.ApiGetAuthorizer;
import org.jeewx.api.third.model.ApiGetAuthorizerRet;
import org.jeewx.api.third.model.ApiGetAuthorizerRetAuthorizer;
import org.jeewx.api.third.model.ApiGetAuthorizerRetAuthortion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.danskin.wechat.api.client.WeiXinOpenApiClient;
import com.danskin.wechat.constant.DanskinConstants;
import com.danskin.wechat.dto.AccumulativeTotalFansDto;
import com.danskin.wechat.dto.IncreasedAndLostFansDto;
import com.danskin.wechat.dto.MsgSendSummaryDto;
import com.danskin.wechat.entity.CrmBrandInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.entity.WxMenuInfo;
import com.danskin.wechat.entity.WxMpFuncInfo;
import com.danskin.wechat.entity.WxMsgReplyDetail;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.CrmBrandInfoService;
import com.danskin.wechat.service.WxCardConfigService;
import com.danskin.wechat.service.WxFansMsgService;
import com.danskin.wechat.service.WxMediaPlatformService;
import com.danskin.wechat.util.ConvertUtils;
import com.danskin.wechat.util.DateTools;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.PropertyUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("app")
public class AppController extends BaseController {

	@Autowired
	private WxMediaPlatformService platformService;

	@Autowired
	private WxCardConfigService cardconfigService;

	@Autowired
	private WxFansMsgService wxFansMsgService;

	@Autowired
	private CrmBrandInfoService crmBrandInfoService;

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Model model) {

		try {
			String component_access_token = getComponentAccessToken();
			// 预授权码
			String preAuthCode = JwThirdAPI.getPreAuthCode(COMPONENT_APPID, component_access_token);
			String url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" + COMPONENT_APPID
					+ "&pre_auth_code=" + preAuthCode + "&redirect_uri=" + PropertyUtil.get("domain")
					+ "/app/auth/callback";
			model.addAttribute("redirectUrl", url);

		} catch (WexinReqException e) {
			LogUtil.error("获取PreAuthCode：" + e.getMessage());
			// e.printStackTrace();
		}

		List<WxMediaPlatform> list = platformService.getListWxMediaPlatform(new HashMap<String, Object>());
		model.addAttribute("mpList", list);

		return "app/list";
	}
	/**
	 * 授权后回调页面（第三方平台跳转返回）
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws AesException
	 * @throws DocumentException
	 * @throws WexinReqException
	 */
	@RequestMapping(value = "/auth/callback")
	public String authCallback(HttpServletRequest request, HttpServletResponse response)
			throws IOException, AesException, DocumentException, WexinReqException {

		// 授权流程完成后，授权页会自动跳转进入回调URI，并在URL参数中返回授权码和过期时间(redirect_url?auth_code=xxx&expires_in=600)
		String auth_code = request.getParameter("auth_code");
		// String expires_in = request.getParameter("expires_in");// 有效期，为10分钟

		String component_access_token = getComponentAccessToken();

		try {
			JSONObject authInfo = JwThirdAPI.getApiQueryAuthInfo(COMPONENT_APPID, auth_code, component_access_token);

			JSONObject authObject = authInfo.getJSONObject("authorization_info");
			String authorizer_appid = authObject.getString("authorizer_appid");
			String authorizer_access_token = authObject.getString("authorizer_access_token");

			ApiGetAuthorizer authorizer = new ApiGetAuthorizer();
			authorizer.setAuthorizer_appid(authorizer_appid);
			authorizer.setComponent_appid(COMPONENT_APPID);
			ApiGetAuthorizerRet authorizerRet = JwThirdAPI.apiGetAuthorizerInfo(authorizer, component_access_token);

			if (authorizerRet != null) {
				ApiGetAuthorizerRetAuthorizer retAuthorizer = authorizerRet.getAuthorizer_info();
				WxMediaPlatform mp = new WxMediaPlatform();
				mp.setAppId(authorizer_appid);
				mp.setNickName(retAuthorizer.getNick_name());
				mp.setHeadImg(retAuthorizer.getHead_img());
				mp.setQrcodeUrl(authorizerRet.getQrcode_url());
				mp.setServiceTypeInfo(ConvertUtils.intToByte(retAuthorizer.getService_type_info().getId()));
				mp.setVerifyTypeInfo(ConvertUtils.intToByte(retAuthorizer.getVerify_type_info().getId()));
				mp.setUserName(retAuthorizer.getUser_name());
				mp.setAlias(retAuthorizer.getAlias());
				mp.setAccessToken(authorizer_access_token);
				mp.setAccessTokenExpires(
						DateTools.getDateTools().operationSecond(new Date(), authObject.getInt("expires_in")));
				mp.setRefreshToken(authObject.getString("authorizer_refresh_token"));
				mp.setStatus(1);
				
				ApiGetAuthorizerRetAuthortion retAuthortion = authorizerRet.getAuthorization_info();

				JSONObject jsonFuncInfo = JSONObject.fromObject(retAuthortion);
				List<WxMpFuncInfo> mpFuncInfos = new ArrayList<WxMpFuncInfo>();

				JSONArray arrFuncInfo = jsonFuncInfo.getJSONArray("func_info");
				for (int i = 0; i < arrFuncInfo.size(); i++) {
					JSONObject funcInfo = arrFuncInfo.getJSONObject(i);
					JSONObject funcCateId = funcInfo.getJSONObject("funcscope_category");

					WxMpFuncInfo fInfo = new WxMpFuncInfo();
					fInfo.setFuncName(this.getFuncName(funcCateId.getInt("id")));
					fInfo.setFuncscopeCategoryId(funcCateId.getInt("id"));
					mpFuncInfos.add(fInfo);
				}

				// 保存公众号信息
				wechatOpService.saveMediaPlatformAndFunc(mp, mpFuncInfos);

				// 创建一个微信会员卡CardID
				//String accessToken = this.getMPWithAccessToken(mp.getId());
				cardconfigService.saveMemberCardConfig(authorizer_access_token, mp);
			}

		} catch (WexinReqException e) {
			// TODO Auto-generated catch block
			LogUtil.error(e.getMessage());
			// e.printStackTrace();
		}

		return "redirect:/app/list";
	}

	@ResponseBody
	@RequestMapping(value = "getCrmBrandInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Object getCrmBrandInfo(int mpId) {

		CrmBrandInfo entity = crmBrandInfoService.selectCrmBrandInfoByMpId(mpId);
		return new AccessResponse<Object>("0", "", entity);
	}

	@RequestMapping(value = "saveCrmBrandInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public Object saveCrmBrandInfo(CrmBrandInfo entity, HttpServletRequest request) throws Exception {

		int rows = crmBrandInfoService.saveCrmBrandInfo(entity);

		return new AccessResponse<Object>("0", "", rows);
	}

	private String getFuncName(int cateId) {
		String funcName = "";
		switch (cateId) {
		case 1:
			break;
		default:
			funcName = "无";
			break;
		}
		return funcName;
	}

	@RequestMapping(value = "dashboard", method = RequestMethod.GET)
	public String dashboard(@RequestParam(value = "beginDate", required = false) String beginDate,
			@RequestParam(value = "endDate", required = false) String endDate, Model model) {
		Long unReadCount = 0L;
		List<IncreasedAndLostFansDto> increasedAndLostFansList = new ArrayList<IncreasedAndLostFansDto>();
		List<IncreasedAndLostFansDto> increasedAndLostFansListTemp = new ArrayList<IncreasedAndLostFansDto>();
		List<AccumulativeTotalFansDto> accumulativeTotalFansList = new ArrayList<AccumulativeTotalFansDto>();
		List<AccumulativeTotalFansDto> accumulativeTotalFansListOne = new ArrayList<AccumulativeTotalFansDto>();
		List<MsgSendSummaryDto> msgSendSummaryCountList = new ArrayList<MsgSendSummaryDto>();
		List<MsgSendSummaryDto> msgSendSummaryCountOneList = new ArrayList<MsgSendSummaryDto>();

		try {
			// 获取mpId
			Integer mpId = getMpId();
			// 获取微信公众号access_token
			String accessToken = getMPWithAccessToken(mpId);

			// 如果开始时间和结束时间为空，给默认值（开始时间是当前时间的前一天，结束时间是当前时间）
			if (StringUtils.isEmpty(beginDate)) {
				beginDate = new SimpleDateFormat("yyyy-MM-dd")
						.format(com.danskin.wechat.util.DateUtils.getBeforeDay(-2));
			}
			if (StringUtils.isEmpty(endDate)) {
				endDate = new SimpleDateFormat("yyyy-MM-dd").format(com.danskin.wechat.util.DateUtils.getBeforeDay(-1));
			}

			// 查询未读消息
			unReadCount = wxFansMsgService.selectWxFansMsgCount(mpId,
					DanskinConstants.WX_FANS_MSG_REPLY_STATUS_NOT_REPLY,
					new SimpleDateFormat("yyyy-MM-dd").parse(beginDate),
					new SimpleDateFormat("yyyy-MM-dd").parse(endDate));

			// 获取微信增减粉丝数
			String increasedAndLostFansString = WeiXinOpenApiClient.createInstance()
					.getIncreasedAndLostWxFansCount(accessToken, endDate, endDate);
			com.alibaba.fastjson.JSONObject increasedAndLostFansJSON = JSON.parseObject(increasedAndLostFansString);
			if (increasedAndLostFansJSON.containsKey("list")) {
				increasedAndLostFansListTemp = JSON.parseArray(increasedAndLostFansJSON.getString("list"),
						IncreasedAndLostFansDto.class);
			}

			// 获取微信累计粉丝数
			String accumulativeTotalFansString = WeiXinOpenApiClient.createInstance()
					.getAccumulativeTotalWxFansCount(accessToken, endDate, endDate);
			com.alibaba.fastjson.JSONObject accumulativeTotalFansJSON = JSON.parseObject(accumulativeTotalFansString);
			if (accumulativeTotalFansJSON.containsKey("list")) {
				accumulativeTotalFansList = JSON.parseArray(accumulativeTotalFansJSON.getString("list"),
						AccumulativeTotalFansDto.class);
			}

			// 获取七天微信累计粉丝数
			String accumulativeTotalFansStringOne = WeiXinOpenApiClient.createInstance()
					.getAccumulativeTotalWxFansCount(accessToken, new SimpleDateFormat("yyyy-MM-dd")
							.format(com.danskin.wechat.util.DateUtils.getBeforeDay(-7)), endDate);
			com.alibaba.fastjson.JSONObject accumulativeTotalFansJSONOne = JSON
					.parseObject(accumulativeTotalFansStringOne);
			if (accumulativeTotalFansJSONOne.containsKey("list")) {
				accumulativeTotalFansListOne = JSON.parseArray(accumulativeTotalFansJSONOne.getString("list"),
						AccumulativeTotalFansDto.class);
			}

			// 获取七天微信消息统计
			String msgSendSummaryCountString = WeiXinOpenApiClient.createInstance().getMsgSendSummaryCount(accessToken,
					new SimpleDateFormat("yyyy-MM-dd").format(com.danskin.wechat.util.DateUtils.getBeforeDay(-7)),
					endDate);
			com.alibaba.fastjson.JSONObject msgSendSummaryCountJSON = JSON.parseObject(msgSendSummaryCountString);
			if (msgSendSummaryCountJSON.containsKey("list")) {
				msgSendSummaryCountList = JSON.parseArray(msgSendSummaryCountJSON.getString("list"),
						MsgSendSummaryDto.class);
			}
			// 处理数据(把相同时间的数据合并为一条数据)
			for (IncreasedAndLostFansDto temp : increasedAndLostFansListTemp) {
				boolean state = false;
				for (IncreasedAndLostFansDto temp1 : increasedAndLostFansList) {
					if (temp1.getRef_date().equals(temp.getRef_date())) {
						int newUserCount = temp1.getNew_user();
						newUserCount += temp.getNew_user();
						temp1.setNew_user(newUserCount);
						int cancalUserCount = temp1.getCancel_user();
						cancalUserCount += temp.getCancel_user();
						temp1.setCancel_user(cancalUserCount);
						state = true;
					}
				}
				if (!state) {
					increasedAndLostFansList.add(temp);
				}
			}
			// 处理数据(把相同时间的数据合并为一条数据)
			for (MsgSendSummaryDto temp : msgSendSummaryCountList) {
				boolean state = false;
				for (MsgSendSummaryDto temp1 : msgSendSummaryCountOneList) {
					if (temp1.getRef_date().equals(temp.getRef_date())) {
						int money = temp1.getMsg_count();
						money += temp.getMsg_count();
						temp1.setMsg_count(money);
						state = true;
					}
				}
				if (!state) {
					msgSendSummaryCountOneList.add(temp);
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		model.addAttribute("unReadCount", unReadCount);
		model.addAttribute("increasedAndLostFansList", increasedAndLostFansList);
		model.addAttribute("accumulativeTotalFansList", accumulativeTotalFansList);
		model.addAttribute("accumulativeTotalFansListOne", accumulativeTotalFansListOne);
		model.addAttribute("msgSendSummaryCountList", msgSendSummaryCountOneList);

		return "app/dashboard";
	}
}
